#!/usr/bin/env python
#coding: utf-8
from models import UserProfile
from functools import wraps
from django.utils.decorators import available_attrs
from django.http import Http404

def get_user_profile(*args, **kwargs):
    request = None
    profile = None

    if args and args[0]: request = args[0]

    if kwargs.get('user', None):
        try:
            profile = UserProfile.objects.get(user = kwargs['user'])
            profile.save()
        except UserProfile.DoesNotExist:
            profile = UserProfile(user = kwargs['user'])
            profile.save()
    elif request and request.user.is_authenticated():
        profile = request.session.get('user_profile', None)
        if not profile: 
            #profile = request.user.get_profile()
            try:
                profile = request.user.get_profile()
                profile.save()
            except Exception as e:
                #request.user.DoesNotExist:
                #assert False
                profile = UserProfile(user = request.user)
                profile.save()
    return profile
    #loginza_profile = update_loginza_userinfo(profile = profile)
    #return loginza_profile or profile

def auth_user_required(func):
    @wraps(func, assigned=available_attrs(func))
    def wrapped(request, *args, **kwargs):
        if request.user:
            profile = get_user_profile(request)
            if profile: 
                kwargs['profile'] = profile
                return func(request, *args, **kwargs)
        raise Http404()

    return wrapped

